import sys

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import QtCore,QtGui
from PyQt5.QtChart import *
import matplotlib.pyplot as plt

from ui_myCalculator import Ui_myCalculator


class dkXx:
    def __init__(self):
        """
        贷款本金、首付款、利率（年）、月利率、租房支出、出租收入、贷款年限、贷款期数、总利息、房屋契税(成交价的1.5%，超过144㎡为3%~5%)
        公共维修基金(成交价的2%~3%，此处按照0计算)、
        补面积差价(面积误差比绝对值在3%以内的，据实结算房价款；面积误差比绝对值超出3%时，买受人有权退房。此处按照0计算)、
        总支出 = 首付＋还款总额 + 收房费用(房屋契税，公共维修基金，补面积差价，此处按照144㎡以内的房屋计算房屋契税)、
        资产总值 = 当前房子可以买出的总额
        """""
        self.dkZe = 0
        self.sf = 0
        self.ll = 0
        self.yll = 0
        self.zfZc = 0
        self.czSr = 0
        self.dkNx = 0
        self.dkZqs = 0
        self.zlx = 0
        self.qs = 0
        # self.ggwx = 0
        self.bmjcj = 0
        self.zzc = 0
        self.zczz = 0
        self.bxList = []
        self.bjList = []


class myCalculator(QWidget):
    def __init__(self,parent = None):
        super(myCalculator, self).__init__(parent)
        self.ui = Ui_myCalculator()
        self.ui.setupUi(self)
        self.setWindowTitle("房贷资产透视")
        self.__chart = None  # 图表
        self.__Series = []  # 当前序列
        self.__curAxis = None  # 当前坐标轴

        self.ui.combo_Type.currentIndexChanged[int].connect(self.resetCreatButton)
        self.init()

    def init(self):
        self.ui.btn_Yg.setEnabled(False)
        self.ui.btn_Yglx.setEnabled(False)
        self.ui.btn_Ygbj.setEnabled(False)
        self.ui.btn_Zzc.setEnabled(False)
        self.ui.btn_Zfzc.setEnabled(False)
        self.ui.btn_Czsr.setEnabled(False)
        self.ui.btn_Fz.setEnabled(False)
        self.ui.btn_Fzl.setEnabled(False)
        self.ui.btn_Sum.setEnabled(False)
        self.ui.btn_Sfzc.setEnabled(False)

        self.ui.lineEdit_ll.setValidator(QDoubleValidator())
        self.ui.lineEdit_sf.setValidator(QDoubleValidator())
        self.ui.lineEdit_zfzc.setValidator(QDoubleValidator())
        self.ui.lineEdit_czsr.setValidator(QDoubleValidator())
        self.ui.lineEdit_dknx.setValidator(QIntValidator())
        self.ui.lineEdit_sum.setValidator(QDoubleValidator())
        self.ui.lineEdit_zczz.setValidator(QDoubleValidator())
        self.ui.combo_Type.setCurrentIndex(-1)
        self.dk = dkXx()
        self.ui.btn_creatExcel.setEnabled(False)
        """
        调试
        """""
        self.ui.lineEdit_ll.setText("4.1")
        self.ui.lineEdit_sf.setText("400000")
        self.ui.lineEdit_sum.setText("1040000")
        self.ui.lineEdit_zczz.setText("1040000")
        self.ui.lineEdit_zfzc.setText("2500")
        self.ui.lineEdit_czsr.setText("1000")
        self.ui.lineEdit_dknx.setText("13")
        self.ui.combo_Type.setCurrentIndex(1)

    @pyqtSlot()
    def on_btn_confirm_clicked(self):
        # flagF = self.checkLineEditIsFloat()
        flagN = self.checkLineEditIsNotNull()
        if not flagN:
            QMessageBox.critical(self,"提示","请输入有效参数",QMessageBox.Yes|QMessageBox.Cancel)
            return
        self.ui.btn_creatExcel.setEnabled(True)
        self.dk.sf = float(self.ui.lineEdit_sf.text())
        self.dk.ll = float(self.ui.lineEdit_ll.text())/100
        self.dk.yll = self.dk.ll/12
        self.dk.dkNx = int(self.ui.lineEdit_dknx.text())
        self.dk.zfZc = float(self.ui.lineEdit_zfzc.text())
        self.dk.czSr = float(self.ui.lineEdit_czsr.text())
        self.dk.dkZe = float(self.ui.lineEdit_sum.text()) - self.dk.sf
        self.dk.dkZqs = self.dk.dkNx * 12
        self.dk.zczz = float(self.ui.lineEdit_zczz.text())
        self.dk.qs = round(float(self.ui.lineEdit_sum.text())*0.015)
        self.calculatorDk()

    def resetCreatButton(self,index):
        self.ui.btn_creatExcel.setEnabled(False)

    @pyqtSlot()
    def on_btn_creatExcel_clicked(self):
        """
        设置模型，选择模型    
        设置数据层次结构，4行4列
        设置水平方向四个头标签文本内容
        """""
        self.model = QStandardItemModel(self.dk.dkZqs, 11)
        self.selectionModel = QItemSelectionModel(self.model)
        self.model.setHorizontalHeaderLabels\
            (["期数", "月供", "月供本金", "月供利息","收房支出","租房支出","出租收入","总支出", "负债", "总支出＋负债", "负债率"])

        if self.ui.combo_Type.currentIndex() == 0:
            for i in self.dk.bjList:
                for j in range(11):
                    item = QStandardItem(str(i[j]))         #  设置单元格内容
                    item.setEditable(False)                 #  设置单元格不可修改
                    item.setTextAlignment(Qt.AlignCenter)
                    self.model.setItem(i[0]-1, j, item)
        elif self.ui.combo_Type.currentIndex() == 1:
            for i in self.dk.bxList:
                for j in range(11):
                    item = QStandardItem(str(i[j]))
                    item.setEditable(False)
                    item.setTextAlignment(Qt.AlignCenter)
                    self.model.setItem(i[0]-1, j, item)
        self.ui.tableView.setModel(self.model)
        self.ui.tableView.setSelectionModel(self.selectionModel)
        oneOrMore = QAbstractItemView.ExtendedSelection
        self.ui.tableView.setSelectionMode(oneOrMore)

        itemOrRow = QAbstractItemView.SelectItems
        self.ui.tableView.setSelectionBehavior(itemOrRow)

        self.ui.tableView.verticalHeader().setDefaultSectionSize(22)
        self.ui.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.ui.tableView.setAlternatingRowColors(True)     # 使用交替颜色绘制背景
        """
        绘制折线图
        """""
        self.__createChart()
        # self.__updateFromChart()

    def calculatorDk(self):
        """"
        等额本金计算
        lx 利息
        zlx 总利息
        bj 本金
        等额本息计算
        yhke 每月应还款总额=(贷款总额*贷款月利率*(1+贷款月利率)^贷款总期数)/(((1+贷款月利率)^贷款总期数)-1)
        bj 本金
        lx 利息
        """""
        if self.ui.combo_Type.currentIndex() == 0:
            self.dk.bjList.clear()
            self.dk.zlx = 0
            self.dk.zzc = self.dk.sf
            ze = self.dk.dkZe
            for i in range(self.dk.dkZqs):
                self.dk.zlx+=self.dk.yll*ze
                ze -= (ze / (self.dk.dkZqs - i))
            for i in range(self.dk.dkZqs):
                bj = self.dk.dkZe/(self.dk.dkZqs-i)
                lx = self.dk.yll*self.dk.dkZe
                tmp = lx+bj
                """
                bjList
                期数,月供,月供本金,月供利息,收房支出,租房支出,出租收入,总支出,负债,总支出＋负债,负债率
                """""
                self.dk.zzc +=tmp
                self.dk.dkZe -= (self.dk.dkZe / (self.dk.dkZqs - i))
                self.dk.zlx -= lx
                # fzhlx =round(self.dk.dkZe+self.dk.zlx,2) if round(self.dk.dkZe+self.dk.zlx,2)>0 else 0
                a = i + 1 if i+1>0 else 0
                b = round(tmp,2) if round(tmp,2)>0 else 0
                c = round(bj, 2) if round(bj, 2)>0 else 0
                d = round(lx, 2) if round(lx, 2)>0 else 0
                e = round(self.dk.zfZc*(i+1),2) if round(self.dk.zfZc*(i+1),2)>0 else 0
                f = round(self.dk.czSr*(i+1),2) if round(self.dk.czSr*(i+1),2)>0 else 0
                g = round(self.dk.zzc,2) if round(self.dk.zzc,2)>0 else 0
                h = round(self.dk.dkZe,2) if round(self.dk.dkZe,2)>0 else 0
                k = round(self.dk.qs,2) if round(self.dk.qs,2)>0 else 0
                t = round(self.dk.zzc + self.dk.dkZe, 2) if round(self.dk.zzc + self.dk.dkZe, 2) > 0 else 0
                fzl = int(((self.dk.dkZe)/self.dk.zczz)*100) if int(((self.dk.dkZe)/self.dk.zczz)*100)>0 else 0
                if i+1<36:
                    self.dk.bjList.append((a, b,c,d,0,e,f,g,h,t,fzl))
                else:
                    self.dk.bjList.append((a, b,c,d,k,e,f,g,h,t,fzl))
        elif self.ui.combo_Type.currentIndex() == 1:
            self.dk.bxList.clear()
            self.dk.zlx = 0
            self.dk.zzc = self.dk.sf
            yhke = (self.dk.dkZe*self.dk.yll* (1 + self.dk.yll) ** self.dk.dkZqs)/ (
                    ((1 + self.dk.yll) ** self.dk.dkZqs)-1)
            self.dk.zlx = self.dk.dkZqs*yhke-self.dk.dkZe
            for i in range(self.dk.dkZqs):
                lx = self.dk.dkZe*self.dk.yll
                bj = yhke - lx
                """
                bxList
                期数,月供,月供本金,月供利息,收房支出,租房支出,出租收入,总支出,负债,总支出＋负债,负债率
                """""
                self.dk.zzc +=yhke
                self.dk.dkZe -= bj
                self.dk.zlx -= lx
                # fz = round(self.dk.dkZe + self.dk.zlx, 2) if round(self.dk.dkZe + self.dk.zlx, 2) > 0 else 0
                a = i + 1 if i+1>0 else 0
                b = round(yhke,2) if round(yhke,2)>0 else 0
                c = round(bj, 2) if round(bj, 2)>0 else 0
                d = round(lx, 2) if round(lx, 2)>0 else 0
                e = round(self.dk.zfZc*(i+1),2) if round(self.dk.zfZc*(i+1),2)>0 else 0
                f = round(self.dk.czSr*(i+1),2) if round(self.dk.czSr*(i+1),2)>0 else 0
                g = round(self.dk.zzc,2) if round(self.dk.zzc,2)>0 else 0
                h = round(self.dk.dkZe,2) if round(self.dk.dkZe,2)>0 else 0
                k = round(self.dk.qs,2) if round(self.dk.qs,2)>0 else 0
                t = round(self.dk.zzc+self.dk.dkZe,2) if round(self.dk.zzc+self.dk.dkZe,2)>0 else 0
                fzl = int(((self.dk.dkZe)/self.dk.zczz)*100) if int(((self.dk.dkZe)/self.dk.zczz)*100)>0 else 0
                if i+1<36:
                    self.dk.bxList.append((a, b,c,d,0,e,f,g,h,t,fzl))
                else:
                    self.dk.bxList.append((a, b,c,d,k,e,f,g,h,t,fzl))
        # print(self.dk.bjList)
        # print(self.dk.bxList)

    def __prepareData(self):
        self.series0 = QLineSeries()
        series1 = QLineSeries()
        series2 = QLineSeries()
        series3 = QLineSeries()
        series4 = QLineSeries()
        series5 = QLineSeries()
        series6 = QLineSeries()
        series7 = QLineSeries()
        series8 = QLineSeries()
        series9 = QLineSeries()
        series10 = QLineSeries()
        """
        ["期数", "月供", "月供本金", "月供利息","收房支出","租房支出","出租收入","总支出", "负债", "总支出＋负债", "负债率"]
        """""
        self.series0.setName("期数")
        series1.setName("月供")
        series2.setName("月供本金")
        series3.setName("月供利息")
        series4.setName("收房支出")
        series5.setName("租房支出")
        series6.setName("出租收入")
        series7.setName("总支出")
        series8.setName("负债")
        series9.setName("总支出+负债")
        series10.setName("负债率")
        self.__Series = []
        if self.ui.combo_Type.currentIndex() == 0:
            for i in range(self.dk.dkZqs):
                self.series0.append(i + 1, self.dk.bjList[i][0])
                series1.append(i + 1, self.dk.bjList[i][1])
                series2.append(i + 1, self.dk.bjList[i][2])
                series3.append(i + 1, self.dk.bjList[i][3])
                series4.append(i + 1, self.dk.bjList[i][4])
                series5.append(i + 1, self.dk.bjList[i][5])
                series6.append(i + 1, self.dk.bjList[i][6])
                series7.append(i + 1, self.dk.bjList[i][7])
                series8.append(i + 1, self.dk.bjList[i][8])
                series9.append(i + 1, self.dk.bjList[i][9])
                series10.append(i + 1, self.dk.bjList[i][10])
        elif self.ui.combo_Type.currentIndex() == 1:
            for i in range(self.dk.dkZqs):
                self.series0.append(i + 1, self.dk.bxList[i][0])
                series1.append(i + 1, self.dk.bxList[i][1])
                series2.append(i + 1, self.dk.bxList[i][2])
                series3.append(i + 1, self.dk.bxList[i][3])
                series4.append(i + 1, self.dk.bxList[i][4])
                series5.append(i + 1, self.dk.bxList[i][5])
                series6.append(i + 1, self.dk.bxList[i][6])
                series7.append(i + 1, self.dk.bxList[i][7])
                series8.append(i + 1, self.dk.bxList[i][8])
                series9.append(i + 1, self.dk.bxList[i][9])
                series10.append(i + 1, self.dk.bxList[i][10])
        self.__Series.append(series1)
        self.__Series.append(series2)
        self.__Series.append(series3)
        self.__Series.append(series4)
        self.__Series.append(series5)
        self.__Series.append(series6)
        self.__Series.append(series7)
        self.__Series.append(series8)
        self.__Series.append(series9)
        self.__Series.append(series10)
        # 创建坐标轴
        self.axisX = QValueAxis()  # X 轴
        self.axisX.setRange(0, self.dk.dkZqs)  # 设置坐标轴范围
        self.axisX.setTitleText("mouth")  # 标题
        self.axisX.setTickCount(self.dk.dkNx+1) #设置刻度线大小
        self.__chart.setAxisX(self.axisX, self.series0) # 设置X轴的数据


    @pyqtSlot()
    def on_btn_Yg_clicked(self):
        axisY = QValueAxis()  # Y 轴
        axisY.setRange(0, 20000)
        axisY.setTitleText("月供")
        self.__chart.addSeries(self.__Series[0])
        # self.__chart.setAxisX(self.axisX, self.__Series[0])
        self.__chart.setAxisY(axisY, self.__Series[0])
        self.ui.btn_Yg.setEnabled(False)

    @pyqtSlot()
    def on_btn_Ygbj_clicked(self):
        axisY = QValueAxis()  # Y 轴
        axisY.setRange(0, 10000)
        axisY.setTitleText("月供本金")
        self.__chart.addSeries(self.__Series[1])
        # self.__chart.setAxisX(self.axisX, self.__Series[1])
        self.__chart.setAxisY(axisY, self.__Series[1])
        self.ui.btn_Ygbj.setEnabled(False)

    @pyqtSlot()
    def on_btn_Yglx_clicked(self):
        axisY = QValueAxis()  # Y 轴
        axisY.setRange(0, 10000)
        axisY.setTitleText("月供利息")
        self.__chart.addSeries(self.__Series[2])
        self.__chart.setAxisY(axisY, self.__Series[2])
        self.ui.btn_Yglx.setEnabled(False)

    @pyqtSlot()
    def on_btn_Zzc_clicked(self):
        axisY = QValueAxis()  # Y 轴
        axisY.setRange(0, self.dk.zczz*1.5)
        axisY.setTitleText("总支出")
        self.__chart.addSeries(self.__Series[6])
        self.__chart.setAxisY(axisY, self.__Series[6])
        self.ui.btn_Zzc.setEnabled(False)

    @pyqtSlot()
    def on_btn_Sfzc_clicked(self):
        axisY = QValueAxis()  # Y 轴
        axisY.setRange(0, self.dk.zczz*0.03)
        axisY.setTitleText("收房支出")
        self.__chart.addSeries(self.__Series[3])
        self.__chart.setAxisY(axisY, self.__Series[3])
        self.ui.btn_Sfzc.setEnabled(False)

    @pyqtSlot()
    def on_btn_Zfzc_clicked(self):
        axisY = QValueAxis()  # Y 轴
        axisY.setRange(0, self.dk.zfZc*self.dk.dkZqs)
        axisY.setTitleText("租房支出")
        self.__chart.addSeries(self.__Series[4])
        self.__chart.setAxisY(axisY, self.__Series[4])
        self.ui.btn_Zfzc.setEnabled(False)

    @pyqtSlot()
    def on_btn_Czsr_clicked(self):
        axisY = QValueAxis()  # Y 轴
        axisY.setRange(0, self.dk.czSr*self.dk.dkZqs)
        axisY.setTitleText("出租收入")
        self.__chart.addSeries(self.__Series[5])
        self.__chart.setAxisY(axisY, self.__Series[5])
        self.ui.btn_Czsr.setEnabled(False)

    @pyqtSlot()
    def on_btn_Fz_clicked(self):
        axisY = QValueAxis()  # Y 轴
        axisY.setRange(0, self.dk.dkZe)
        axisY.setTitleText("负债")
        self.__chart.addSeries(self.__Series[7])
        self.__chart.setAxisY(axisY, self.__Series[7])
        self.ui.btn_Fz.setEnabled(False)

    @pyqtSlot()
    def on_btn_Sum_clicked(self):
        axisY = QValueAxis()  # Y 轴
        axisY.setRange(self.dk.zczz,  self.dk.zczz*1.5)
        axisY.setTitleText("总支出+负债")
        self.__chart.addSeries(self.__Series[-2])
        self.__chart.setAxisY(axisY, self.__Series[-2])
        self.ui.btn_Sum.setEnabled(False)

    @pyqtSlot()
    def on_btn_Fzl_clicked(self):
        axisY = QValueAxis()  # Y 轴
        axisY.setRange(0, 100)
        axisY.setTitleText("负债率:%")
        self.__chart.addSeries(self.__Series[-1])
        self.__chart.setAxisY(axisY, self.__Series[-1])
        self.ui.btn_Fzl.setEnabled(False)

    def __createChart(self):
        self.ui.btn_Yg.setEnabled(True)
        self.ui.btn_Yglx.setEnabled(True)
        self.ui.btn_Ygbj.setEnabled(True)
        self.ui.btn_Zzc.setEnabled(True)
        self.ui.btn_Zfzc.setEnabled(True)
        self.ui.btn_Czsr.setEnabled(True)
        self.ui.btn_Fz.setEnabled(True)
        self.ui.btn_Fzl.setEnabled(True)
        self.ui.btn_Sum.setEnabled(True)
        self.ui.btn_Sfzc.setEnabled(True)
        self.__chart = QChart()
        self.__chart.setTitle("贷款信息折线图")
        self.ui.chartView.setChart(self.__chart)
        self.ui.chartView.setRenderHint(QPainter.Antialiasing)
        self.ui.chartView.setRubberBand(QChartView.HorizontalRubberBand)

        self.__prepareData()


    def checkLineEditIsFloat(self):
        flag = True
        if not isinstance(float(self.ui.lineEdit_ll.text()),float):
            flag = False
        if not isinstance(float(self.ui.lineEdit_czsr.text()),float):
            flag = False
        if not isinstance(float(self.ui.lineEdit_sf.text()),float):
            flag = False
        if not isinstance(float(self.ui.lineEdit_sum.text()),float):
            flag = False
        if not isinstance(int(self.ui.lineEdit_dknx.text()),int):
            flag = False
        if not isinstance(float(self.ui.lineEdit_zfzc.text()),float):
            flag = False
        if not isinstance(float(self.ui.lineEdit_zczz.text()),float):
            flag = False
        if self.ui.combo_Type.currentIndex() != 0 and self.ui.combo_Type.currentIndex() != 1:
            flag = False
        return flag

    def checkLineEditIsNotNull(self):
        flag = True
        if self.ui.lineEdit_ll.text()=="":
            flag = False
        if self.ui.lineEdit_czsr.text()=="":
            flag = False
        if self.ui.lineEdit_sf.text()=="":
            flag = False
        if self.ui.lineEdit_sum.text()=="":
            flag = False
        if self.ui.lineEdit_dknx.text()=="":
            flag = False
        if self.ui.lineEdit_zfzc.text()=="":
            flag = False
        if self.ui.lineEdit_zczz.text()=="":
            flag = False
        if self.ui.combo_Type.currentIndex() != 0 and self.ui.combo_Type.currentIndex() != 1:
            flag = False
        return flag

if __name__ == '__main__':
    app = QApplication(sys.argv)
    form = myCalculator()
    form.show()
    sys.exit(app.exec())

